<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <!-- 今日概览 -->
      <el-row :gutter="20" class="overview-row">
        <el-col :span="6" v-for="(item, index) in overviewData" :key="index">
          <el-card :shadow="'hover'" class="overview-card">
            <div slot="header" class="card-header">
              <span>{{ item.title }}</span>
            </div>
            <div class="card-content">
              <i :class="item.icon" :style="{ fontSize: '48px', color: item.color }"></i>
              <h2>{{ item.value }}</h2>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 可售床位 -->
      <el-row :gutter="20" class="bed-row">
        <el-col :span="8">
          <el-card shadow="hover" class="bed-card">
            <div slot="header" class="card-header">
              <span>可售床位</span>
            </div>
            <div class="card-content">
              <i class="el-icon-bed" style="font-size: 48px; color: #409EFF;"></i>
              <h2>20</h2>
            </div>
          </el-card>
        </el-col>

        <!-- 业务趋势模块 -->
        <el-col :span="8">
          <el-card shadow="hover" class="trend-card">
            <div slot="header" class="card-header">
              <span>业务趋势</span>
            </div>
            <div ref="businessTrendChartContainer" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 本月业绩排行 -->
        <el-col :span="8">
          <el-card shadow="hover" class="performance-card">
            <div slot="header" class="card-header">
              <span>本月业绩排行</span>
            </div>
            <el-table :data="performanceList" style="width: 100%">
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="performance" label="业绩" width="120"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>员工出勤率</span>
            </div>
            <el-table :data="attendanceData" style="width: 100%">
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="attendance" label="出勤率%" width="120"></el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 图表区域 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>出勤率图表</span>
            </div>
            <div ref="attendanceChartContainer" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 其他图表 -->
      <el-row :gutter="20">
        <el-col :span="12">
      <el-card shadow="hover">
        <div slot="header" class="clearfix">
          <span>任务完成率</span>
        </div>
        <div ref="taskCompletionChartContainer" style="height: 300px;"></div>
      </el-card>
    </el-col>

    <el-col :span="12">
      <el-card shadow="hover">
        <div slot="header" class="clearfix">
          <span>房间使用率</span>
        </div>
        <div ref="roomUsageChartContainer" style="height: 300px;"></div>
      </el-card>
    </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'DashboardHome',
  components: {
    AsideLayout
  },
  data() {
    return {
      overviewData: [],
      performanceList: [],
      attendanceData: [],
      businessTrendChartOptions: {},
      attendanceChartOptions: {},
      taskCompletionChartOptions: {},
      roomUsageChartOptions: {}
    }
  },
  mounted() {
    this.fetchOverviewData();
    this.fetchPerformanceData();
    this.fetchAttendanceData();
    this.fetchBusinessTrendData();
    this.fetchTaskCompletionData();
    this.fetchRoomUsageData();
  },
  watch: {
    businessTrendChartOptions: {
      handler() {
        this.renderChart('businessTrendChartContainer', this.businessTrendChartOptions);
      },
      deep: true
    },
    attendanceChartOptions: {
      handler() {
        this.renderChart('attendanceChartContainer', this.attendanceChartOptions);
      },
      deep: true
    },
    taskCompletionChartOptions: {
      handler() {
        this.renderChart('taskCompletionChartContainer', this.taskCompletionChartOptions);
      },
      deep: true
    },
    roomUsageChartOptions: {
      handler() {
        this.renderChart('roomUsageChartContainer', this.roomUsageChartOptions);
      },
      deep: true
    }
  },
  methods: {
    fetchOverviewData() {
      axios.get('http://localhost:3000/api/overview')
        .then(response => {
          this.overviewData = [
            { title: '在院老人', icon: 'el-icon-user-solid', color: '#409EFF', value: response.data.elderlyCount },
            { title: '在岗护工', icon: 'el-icon-s-custom', color: '#67C23A', value: response.data.nurseCount },
            { title: '完成任务数', icon: 'el-icon-s-order', color: '#E6A23C', value: response.data.taskCount },
            { title: '房间使用率', icon: 'el-icon-s-home', color: '#F56C6C', value: response.data.roomUsage }
          ];
        })
        .catch(error => {
          console.error('Error fetching overview data:', error);
        });
    },
    fetchPerformanceData() {
      axios.get('http://localhost:3000/api/performance')
        .then(response => {
          this.performanceList = response.data;
        })
        .catch(error => {
          console.error('Error fetching performance data:', error);
        });
    },
    fetchAttendanceData() {
      axios.get('http://localhost:3000/api/attendance')
        .then(response => {
          console.log('Attendance Data:', response.data); // 添加日志
          this.attendanceData = response.data;

          // 生成图表选项
          this.attendanceChartOptions = {
            title: {
              text: '员工出勤率',
              left: 'center'
            },
            tooltip: {
              trigger: 'item'
            },
            series: [
              {
                name: '出勤率',
                type: 'pie',
                radius: '50%',
                data: response.data.map(item => ({
                  name: item.name,
                  value: item.attendance
                })),
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };

          console.log('Attendance Chart Options:', this.attendanceChartOptions); // 添加日志

          // 渲染图表
          this.renderChart('attendanceChartContainer', this.attendanceChartOptions);
        })
        .catch(error => {
          console.error('Error fetching attendance data:', error);
        });
    },
    fetchBusinessTrendData() {
      axios.get('http://localhost:3000/api/business-trend')
        .then(response => {
          this.businessTrendChartOptions = {
            title: {
              text: '业务趋势',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: response.data.map(item => item.month)
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '业务量',
                type: 'line',
                data: response.data.map(item => item.businessVolume)
              }
            ]
          };
        })
        .catch(error => {
          console.error('Error fetching business trend data:', error);
        });
    },
    fetchTaskCompletionData() {
      axios.get('http://localhost:3000/api/task-completion')
        .then(response => {
          if (Array.isArray(response.data)) {
            this.taskCompletionChartOptions = {
              title: {
                text: '任务完成率',
                left: 'center'
              },
              tooltip: {
                trigger: 'axis'
              },
              xAxis: {
                type: 'category',
                data: response.data.map(item => item.date)
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  name: '完成率',
                  type: 'line',
                  data: response.data.map(item => parseFloat(item.completionRate))
                }
              ]
            };
            this.initChart('taskCompletionChartContainer', this.taskCompletionChartOptions);
          } else {
            console.error('Error: response.data is not an array');
          }
        })
        .catch(error => {
          console.error('Error fetching task completion data:', error);
        });
    },
    fetchRoomUsageData() {
      axios.get('http://localhost:3000/api/room-usage')
        .then(response => {
          if (Array.isArray(response.data)) {
            this.roomUsageChartOptions = {
              title: {
                text: '房间使用率',
                left: 'center'
              },
              tooltip: {
                trigger: 'axis'
              },
              xAxis: {
                type: 'category',
                data: response.data.map(item => item.month)
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  name: '使用率',
                  type: 'line',
                  data: response.data.map(item => parseFloat(item.usageRate))
                }
              ]
            };
            this.initChart('roomUsageChartContainer', this.roomUsageChartOptions);
          } else {
            console.error('Error: response.data is not an array');
          }
        })
        .catch(error => {
          console.error('Error fetching room usage data:', error);
        });
    },
    renderChart(containerRef, options) {
      const chart = echarts.init(this.$refs[containerRef]);
      chart.setOption(options);
    }
  }
}
</script>

<style scoped>
.el-main {
  padding: 20px;
}

.overview-row, .bed-row, .performance-row, .trend-row {
  margin-bottom: 20px;
}

.overview-card, .bed-card, .performance-card, .trend-card {
  transition: transform 0.3s;
}

.overview-card:hover, .bed-card:hover, .performance-card:hover, .trend-card:hover {
  transform: translateY(-5px);
}

.card-header {
  font-weight: bold;
  color: #333;
}

.card-content {
  text-align: center;
  margin-top: 20px;
}

.v-chart {
  height: 300px;
}
</style>